package Servlet;

import Entity.Document;
import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import javax.jdo.PersistenceManager;

public class Upload extends HttpServlet {
    private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();

    public void doPost(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {

        String name = req.getParameter("foo");
        if(!name.equals(""))
        {
            Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
            BlobKey blobKey = blobs.get("myFile");

            if (blobKey == null) {
                res.sendRedirect("/");
            } else {
                
                PersistenceManager pm = PMF.get().getPersistenceManager();
                Document doc = new Document();
                doc.setKey(blobKey.getKeyString());
                doc.setName(name);
                try
                {
                   pm.makePersistent(doc);
                }
                finally{
                    pm.close();
                }
                 
                //res.sendRedirect("/serve?blob-key=" + blobKey.getKeyString());
            }
        }
   }
}